package com.yuanfeng.action.front.buy.web;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.yuanfeng.pojo.Books;
import org.apache.struts2.ServletActionContext;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
 * 购物车模块的Action
 *
 * @author yuanfeng
 *
 */
public class BuyAction extends ActionSupport implements ModelDriven<Books> {
	/**
	 * 构造一个book对象用于模型驱动
	 */
	private Books book = new Books();

	// 把一本书加到购物车中
	public String addToCar(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession(true);
		// 1)接收用户购买的图书的信息
	 	book = this.getModel();
		System.out.println("购物车乱码:"+book);
		// 2)创建一个Map集合来保存购物车的所有图书信息
		// 先从session中读取购物车的数据
		Map<String, Books> car = (Map<String, Books>) session.getAttribute("car");
		if (car == null) {
			// 第一次访问
			car = new HashMap<String, Books>();
		}
		/**
		 * 数量问题： 1）如果是当前购物车中没有这本书，则为1 2）如果当前购物车中有了这本书，则为 （当前数量+1）
		 */
		if (car.containsKey(book.getId())) {
			// 获取购物现有的数量+1
			book.setAmt(car.get(book.getId()).getAmt() + 1);
		} else {
			book.setAmt(1);
		}

		// 3)把图书放入购物车对象中
		car.put(book.getId(), book);

		// 4)把购物车对象放入session中
		session.setAttribute("car", car);
		// 5)跳转到购物车jsp页面
		return "addToCar";
	}

	/**
	 * 修改购物车的图书数量(加或减)
	 * @return
	 */
	public String modifyCar(){

		HttpServletRequest request = ServletActionContext.getRequest();
		String bookId = request.getParameter("id");
		String num = request.getParameter("num");// 获取是+还是-
		Integer add = Integer.parseInt(num);
		bookId = bookId.trim();
		Map<String, Books> car = (Map<String, Books>) request.getSession().getAttribute("car");
		int result = 0;
		if (car.containsKey(bookId)) {
			Books book = car.get(bookId);
			book.setAmt(book.getAmt() + add);
			if (book.getAmt() == 0) {
				car.remove(bookId);
				result = 0;
			}
			result = book.getAmt();
		}
		return "modifyCar";
	}

	/**
	 *  清空session购物车中的数据
	 * @return
	 */
	public String clearCar(){

		HttpServletRequest request = ServletActionContext.getRequest();
		// 删除session数据
		request.getSession().removeAttribute("car");
		// 重新跳转到购物车首页
		return "clearCar";
	}

	/**
	 * 得到book的对象
	 * @return
	 */
	@Override
	public Books getModel() {
		return book;
	}
}